﻿using BarcodeDelay.bean;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class WeightHelperGen
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListWeightBarcodes = new ArrayList();
        public event Action weightEvent;
        public DateTime dtLastKeepAlive = System.DateTime.Now;

        private static WeightHelperGen instance;
        public static WeightHelperGen Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new WeightHelperGen();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        public void BeginAnalyThread(ArrayList arListBarCodes, string anayType)
        {
            try
            {
                initLog();
                m_arListWeightBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }


                m_arListWeightBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ParameterizedThreadStart(parseWeight));
                fThreadDep.Start((object)arListBarCodes);

                fThreadDep.IsBackground = true;
              

            }
            catch (Exception ex)
            {

            }
        }


        public bool keepAlive(string  barcode,string token,string pickName)
        {
            bool findRoadMap = false;
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListDepResultTmp = new ArrayList();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();

                DateTime dtStart = System.DateTime.Now;
                int intProcess = 0;
                string httpRes = "";
                StoParams.Instance.resMsg = "";
                intProcess++;
                ArrayList arListAllGXTask = new ArrayList();

                string orderSource = "";
                string curSiteToken = "";
                dtLastKeepAlive = System.DateTime.Now;
                ArrayList arListRoadMap = JTDelayHelper.Instance.getRoadMapByToken(barcode, out httpRes, token);
                if (!httpRes.Contains("成功"))
                {
                    logHelp.LogHelper.Instance.writeLog(pickName+" "+barcode + " 请求失败 " + httpRes);
                    StoParams.Instance.resMsg = StoParams.Instance.resMsg + " " + httpRes;
                    weightEvent.Invoke();
                    System.Threading.Thread.Sleep(100);
                    resMsg = "请求失败";
                    return findRoadMap;
                }
                if (httpRes.Contains("成功") && arListRoadMap.Count == 0)
                {
                    logHelp.LogHelper.Instance.writeLog(pickName + " " + barcode + " 心跳请求成功 " + "快件未发出");
                    resMsg = "无路由信息";
                    weightEvent.Invoke();
                    findRoadMap = true;
                    return findRoadMap;
                }
                if(arListRoadMap.Count>1)
                {
                    findRoadMap = true;
                }

                logHelp.LogHelper.Instance.writeLog(pickName + " " + barcode + " 心跳保持成功 ");




            }
            catch (Exception ex)
            {
                logHelp.LogHelper.Instance.writeLog(" 心跳保持异常 " + ex.ToString());
            }
            return findRoadMap;



        }

        public void parseWeight(object arListBarcodes)
        {
            bool findWeight = false;
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListDepResultTmp = new ArrayList();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int intProcess = 0;
                string httpRes = "";
                StoParams.Instance.resMsg = "";
                foreach (ParcelBean parcelBean in (ArrayList)arListBarcodes)
                //foreach (string strBarCode in (ArrayList)arListBarcodes)
                {
                    //logHelp.LogHelper.Instance.writeLog(strBarCode + " 开始执行查重");
                    string strBarCode = parcelBean.wayBill;
                    intProcess++;
                    ArrayList arListAllGXTask = new ArrayList();
                    string pickName = "";
                    string orderSource = "";
                    string curSiteToken = "";
                    //if (!UtilityHelp.Instance.resetToken(strBarCode,out pickName,out orderSource,out curSiteToken))
                    {
                        /*if (curSiteToken == "")
                        {
                            StoParams.Instance.htResWechat[strBarCode] = " 发件网点 " + pickName + " 登录失效";
                            continue;
                        }
                        logHelp.LogHelper.Instance.writeLog(strBarCode + " 未找到匹配网点"+ pickName);
                        System.Threading.Thread.Sleep(100);*/
                        //StoParams.Instance.htResWechat[strBarCode] = " 未找到匹配网点 ";
                    }

                    ArrayList arListRoadMap = JTDelayHelper.Instance.getRoadMap(strBarCode, out httpRes, arListAllGXTask);
                    if (!httpRes.Contains("成功"))
                    {
                        logHelp.LogHelper.Instance.writeLog(strBarCode + " 请求失败 "+ httpRes);
                        StoParams.Instance.resMsg = StoParams.Instance.resMsg+" "+httpRes;
                        System.Threading.Thread.Sleep(100);
                        resMsg = "请求失败";
                        StoParams.Instance.htResWechat[strBarCode] = resMsg;
                        if(weightEvent!=null)
                        {
                            weightEvent.Invoke();
                        }
                        
                        continue;
                    }
                    if (httpRes.Contains("成功")&& arListRoadMap.Count==0)
                    {
                        logHelp.LogHelper.Instance.writeLog(strBarCode + " 请求失败 " + "快件未发出");
                        resMsg = "无路由信息";
                        StoParams.Instance.htResWechat[strBarCode] = resMsg;
                        if (weightEvent != null)
                        {
                            weightEvent.Invoke();
                        }                            
                        continue;
                    }
                    string siteName = "";
                    string weight = JTDelayHelper.Instance.getWeightByRoad(arListRoadMap,out siteName);
                    parcelBean.lanshouSite = siteName;
                    StoParams.Instance.htResWechat[strBarCode] = "重量："+ weight+"kg";
                    StoParams.Instance.currentBarcode = strBarCode;
                    StoParams.Instance.resMsg = StoParams.Instance.resMsg+"\r\n" +pickName + " "+strBarCode + " 重量：" + weight;
                    logHelp.LogHelper.Instance.writeLog(pickName+" "+strBarCode + " 获取重量 " + weight);
                    //resMsg = StoParams.Instance.resMsg;
                    


                }
                if(weightEvent!=null)
                {
                    weightEvent.Invoke();
                }
                
                Random ran = new Random();
                //Thread.Sleep(50);



            }
            catch (Exception ex)
            {
                logHelp.LogHelper.Instance.writeLog(" 获取重量异常 " + ex.ToString());
            }
            int tiot = queryServerResTime;
           


        }






        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadDep.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }

    
            }
            catch (Exception ex)
            {

            }
        }


        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
